<template>
  <div class="slider">
    <div class="input" ref="input" :value="value" :max="max" :min="min" :step="step" />
    <div class="line" :style="{width:lineWidth+'px'}"></div>
    <div class="tip" @touchstart="ontouchstart" @touchmove="ontouchmove" :style="{transform:'translate3d('+tipLeft+'px,0,0)'}">{{showValue}}</div>
  </div>
</template>

<script>
export default {
  name: 'slider',
  data(){
    return{
      sliderWidth:0,
      dragWidth:100,
      startX:0,
      lineWidth:0,
      tipLeft:0,
      showValue:this.value
    }
  },
  props: {
    value:Number,
    max:Number,
    min:Number,
    step:Number
  },
  methods:{
    ontouchstart(e){
      this.startX = e.changedTouches[0].pageX-this.tipLeft
    },
    ontouchmove(e){
      let moveX = e.changedTouches[0].pageX,
        moveLeft = moveX-this.startX,
        maxLeft=this.sliderWidth-this.dragWidth,
        minLeft=maxLeft*this.min/this.max
      if(moveLeft>=maxLeft)moveLeft=maxLeft
      if(moveLeft<=minLeft)moveLeft=minLeft
      this.lineWidth=this.tipLeft=moveLeft
      let value=moveLeft/(this.sliderWidth-this.dragWidth)*this.max
      if(value>=this.showValue+this.step)this.showValue=this.showValue+this.step
      if(value<=this.showValue-this.step)this.showValue=this.showValue-this.step
      if(value==this.max)this.showValue=this.max
      if(value==this.min)this.showValue=this.min
      e.preventDefault()
    }
  },
  mounted(){
    this.sliderWidth=this.$refs.input.offsetWidth
    let moveX = (this.sliderWidth-this.dragWidth)*this.value/this.max
    this.lineWidth=this.tipLeft=moveX
  }
}
</script>

<style lang="less" scoped>
  @width: 100px;
  @height: 25px;
  @top: (@height - 6px)/2;
  @radius: 2px;
  .slider{
    width: 92%;
    height: 6px;
    margin: 0 auto;
    position: relative;
    text-align: right;
    .input{
      width:100%;
      height:100%;
      border:0;
      border-radius: @radius;
      background-color:#ddd;
      display: block;
    }
    .tip{
      width:@width;
      line-height:@height;
      background-size: 100% auto;
      background-image: url(../img/slider.png);
      position: absolute;
      text-align: center;
      top: -@top;
      font-size: 14px;
      z-index: 0;
    }
    .line{
      width:0px;
      height:100%;
      position:absolute;
      border-radius: @radius;
      top:0px;
      left:0px;
      z-index:900;
      background:#d21a1a;
    }
  }
</style>
